package com.huntmobi.springsecuritydemo.base.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huntmobi.springsecuritydemo.base.enums.ContextTypeEnum;
import com.huntmobi.springsecuritydemo.base.enums.HttpEnum;
import com.huntmobi.springsecuritydemo.base.enums.TokenEnum;
import com.huntmobi.springsecuritydemo.base.http.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *
 * @Author：zouzhimin
 * @description：登录退出处理
 * @date：crealed in 11:59 2020/7/7
 * </P>
 **/
@Component
public class JsonLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        String authHeader = httpServletRequest.getHeader(TokenEnum.TOKENHEADER.getMsg());
        if (authHeader != null && authHeader.startsWith(TokenEnum.TOKENPREFIX.getMsg())) {
            final String authToken = authHeader.replaceAll(TokenEnum.TOKENPREFIX.getMsg(),"");
            //删除token
            redisTemplate.delete(authToken);
        }
        httpServletResponse.setContentType(ContextTypeEnum.JSONUTF8.getContextType());
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(Response.success(HttpEnum.LOGOUTSUS.getMsg())));
    }
}
